package com.qf.ability.auth.controller;

import com.alibaba.fastjson.JSON;
import com.qf.ability.auth.protocol.input.SysRoleInput;
import com.qf.ability.auth.service.SysRoleService;
import com.qf.common.core.base.R;
import com.qf.common.core.base.RetUtils;
import com.qf.data.entity.auth.SysRole;
import com.qf.data.entity.auth.vo.SysRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/sys/role")
@Slf4j
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 查询所有角色
     * @return
     */
    @PreAuthorize("hasAuthority('/SysRoleManager')")
    @RequestMapping("/queryAll")
    public R queryAll(){
        List<SysRole> list = sysRoleService.list();
        return RetUtils.createSucc(list);
    }

    /**
     * 根据用户id查询对应的角色列表
     * @param uid
     * @return
     */
    @RequestMapping("/queryRolesByUid")
    public R queryRolesByUid(Long uid){
        List<SysRoleVo> sysRoles = sysRoleService.queryRolesByUid(uid);
        return RetUtils.createSucc(sysRoles);
    }

    /**
     * 修改对应用户的角色
     * @return
     */
    @RequestMapping("/updateUserRole")
    public R updateUserRole(Long uid, String rids){
        List<Long> ridsList = JSON.parseArray(rids, Long.class);
        log.debug("[update-user-role] - 修改用户的角色关系 - 用户id:{} - 角色id:{}", uid, ridsList);

        //修改用户角色
        sysRoleService.updateUserRoles(uid, ridsList);
        return RetUtils.createSucc(true);
    }

    /**
     * 新增角色
     * @return
     */
    @RequestMapping("/insert")
    public R insert(SysRoleInput input){
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(input, sysRole);
        sysRoleService.save(sysRole);
        return RetUtils.createSucc(true);
    }
}
